//using System;
using System.Collections.Generic;
using Storyteller.Framework.Math;

namespace Storyteller.Framework.Graphics
{
	public class TextureDictionary
	{
		public TextureDictionary(string filePath)
		{
			System.IO.StreamReader sr = new System.IO.StreamReader(filePath);
			string jsonText = sr.ReadToEnd();
			sr.Close();
			
			var data = LitJson.JsonMapper.ToObject<TextureDictionaryData>(jsonText);
			
			foreach(var frame in data.frames)
			{
				TextureRegion textureRegion = new TextureRegion();
				textureRegion.Bounds = new Storyteller.Framework.Math.Rectangle(frame.frame.x, frame.frame.y, frame.frame.w, frame.frame.h);
				textureRegion.Rotated = frame.rotated;

				textureRegion.OriginTopLeft = new Vector2((0 - (frame.spriteSourceSize.x)) / (float)frame.spriteSourceSize.w,
					(0 - (frame.spriteSourceSize.y)) / (float)frame.spriteSourceSize.h);

				textureRegion.OriginCenter = new Vector2(((frame.sourceSize.w / 2.0f) - (frame.spriteSourceSize.x)) / (float)frame.spriteSourceSize.w,
					((frame.sourceSize.h / 2.0f) - (frame.spriteSourceSize.y)) / (float)frame.spriteSourceSize.h);

				textureRegion.OriginBottomRight = new Vector2((frame.sourceSize.w - (frame.spriteSourceSize.x)) / (float)frame.spriteSourceSize.w,
					(frame.sourceSize.h - (frame.spriteSourceSize.y)) / (float)frame.spriteSourceSize.h);

				regions[frame.filename] = textureRegion;
			}
		}
		
		public bool ContainsTexture(string textureName)
		{
			return regions.ContainsKey(textureName);
		}
		
		public TextureRegion GetRegion(string textureName)
		{
			TextureRegion region;
			
			if(regions.TryGetValue(textureName, out region))
				return region;
			return null;
		}
		
		Dictionary<string, TextureRegion> regions = new Dictionary<string, TextureRegion>();		
		
		public class Rectangle
		{
			public int x { get; set; }
			public int y { get; set; }
			public int w { get; set; }
			public int h { get; set; }
		}
		
		public class Dimensions
		{
			public int w { get; set; }
			public int h { get; set; }
		}
		
		public class Frame
		{
			public string filename { get; set; }
			public Rectangle frame { get; set; }
			public bool rotated { get; set; }
			public bool trimmed { get; set; }
			public Rectangle spriteSourceSize { get; set; }
			public Dimensions sourceSize { get; set; }
		}
		
		public class Meta
		{
			public string app { get; set; }
			public string version { get; set; }
			public string image { get; set; }
			public string format { get; set; }
			public Dimensions size { get; set; }
			public string scale { get; set; }
			public string smartupdate { get; set; }
		}
		
		public class TextureDictionaryData
		{
			public Frame[] frames { get; set; }
			public Meta meta { get; set; }
		}
		
	}
}

